﻿/*
 * modbusrtumaster.cpp
 *
 *  Created on: 2017年3月1日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_PROTOCOL DM_API_EXPORT

#include <dm/os/protocol/modbusrtumaster.hpp>
#include <dm/os/log/logger.hpp>

namespace dm{
namespace os{
namespace protocol{

static const char* logModule = "CModbusRtuMaster.protocol.os.dm";

CModbusRtuMaster::CModbusRtuMaster():dm::protocol::CProtocol(),
		dm::protocol::CModbusRtuMaster(),dm::os::protocol::CProtocolMasters(),
		m_modbusAddrs(NULL),m_nextDevIndex(-1){
	log().debug(THISMODULE "创建对象");
}

CModbusRtuMaster::~CModbusRtuMaster(){
	log().debug(THISMODULE "销毁对象");
	if( m_modbusAddrs )
		delete [] m_modbusAddrs;
}

void CModbusRtuMaster::setSubDevNum( int num ){
	setDeviceCount(num);

	if( m_modbusAddrs!=NULL )
		delete [] m_modbusAddrs;

	if( num>0 ){
		m_modbusAddrs = new address_t[num];
	}else{
		m_modbusAddrs = NULL;
	}
}

void CModbusRtuMaster::setCurDev( int idx ){
	dm::os::protocol::CProtocolMasters::setCurDev(idx);
	setModbusAddr(curAddress());
}

void CModbusRtuMaster::setSubAddress( int idx,address_t addr ){
	if( idx>=0 && idx<getDevcieCount() )
		m_modbusAddrs[idx] = addr;
}

CModbusRtuMaster::address_t CModbusRtuMaster::getSubAddress( int idx )const{
	if( idx>=0 && idx<getDevcieCount() )
		return m_modbusAddrs[idx];
	else
		return 0;
}

bool CModbusRtuMaster::moveNextOver(){
	++m_nextDevIndex;
	if( m_nextDevIndex>=getSubDevNum() ){
		m_nextDevIndex = 0;
		return true;
	}else
		return false;
}

CModbusRtuMaster::EAction CModbusRtuMaster::taskEnd_remoteControl( const ts_t& ts,const rts_t& rts ){
	// 重载本函数，主要是为了防止严格问答模式下，数据更新过慢
	EAction action = dm::os::protocol::CProtocolMasters::taskEnd_remoteControl(ts,rts);
//	log().debug(THISMODULE "防止状态更新被覆盖，关闭消息");
	enableRequestMsgCheck(false);
	return action;
}

CModbusRtuMaster::EAction CModbusRtuMaster::taskEnd_parameters( const ts_t& ts,const rts_t& rts ){
	EAction action = dm::os::protocol::CProtocolMasters::taskEnd_parameters(ts,rts);
//	log().debug(THISMODULE "防止更新被覆盖，关闭消息");
	enableRequestMsgCheck(false);
	return action;
}

CModbusRtuMaster::EAction CModbusRtuMaster::taskEnd_call( const ts_t& /*ts*/,const rts_t& /*rts*/ ){
	if( m_taskCall==Timeout )
		moveNextOver();

	m_taskCall = None;
	// 召唤结束后，允许新的任务
//	log().debug(THISMODULE "开启消息");
	enableRequestMsgCheck(true);
	return Action_Nothing;
}

}
}
}


